<template>
    <div class="form-designer">
        <!-- 添加工具栏 -->
        <div class="toolbar">
            <div class="toolbar-left">
                <h2 class="toolbar-title">表单设计器</h2> <!-- 添加标题并调整样式 -->
            </div>
            <div class="toolbar-right">
                <el-button type="primary" @click="handleSave">
                    <el-icon>
                        <Download />
                    </el-icon>
                    保存设计
                </el-button>
                <el-button @click="handleClear">
                    <el-icon>
                        <Delete />
                    </el-icon>
                    清空设计
                </el-button>
            </div>
        </div>

        <el-container>
            <!-- 左侧组件列表和暂存区 -->
            <el-aside width="250px" class="left-aside">
                <el-tabs type="border-card" class="full-height-tabs">
                    <!-- 组件列表 -->
                    <el-tab-pane label="组件">
                        <div class="components-grid">
                            <div v-for="item in COMPONENT_LIST" :key="item.type" class="component-item" draggable="true"
                                @dragstart="handleDragStart($event, item.type)">
                                <el-icon>
                                    <component :is="item.icon" />
                                </el-icon>
                                <span>{{ item.label }}</span>
                            </div>
                        </div>
                    </el-tab-pane>

                    <!-- 暂存区 -->
                    <el-tab-pane label="暂存区">
                        <div class="temp-storage" @dragover.prevent @drop="handleDropToStorage">
                            <template v-if="storageItems.length">
                                <div v-for="(item, index) in storageItems" :key="index" class="storage-item"
                                    draggable="true" @dragstart="handleDragStart($event, item.type, true)">
                                    <el-icon>
                                        <component :is="item.icon" />
                                    </el-icon>
                                    <span>{{ item.label }}</span>
                                    <el-icon class="delete-icon" @click.stop="removeFromStorage(index)">
                                        <Delete />
                                    </el-icon>
                                </div>
                            </template>
                            <el-empty v-else description="从设计区拖拽组件到此处暂存" />
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </el-aside>

            <!-- 中间设计区域 -->
            <el-main class="main-container">
                <div class="design-area" @dragover.prevent @drop.prevent="handleDrop">
                    <template v-if="formItems.length">
                        <div v-for="(item, index) in formItems" :key="item.id" class="form-item"
                            :class="{ 'is-selected': selectedIndex === index }" draggable="true"
                            @click="handleSelectItem(index)"
                            @dragstart="handleDesignItemDragStart($event, item, index)">
                            <el-form-item :label="item.label">
                                <component :is="item.component" v-bind="item.props" />
                            </el-form-item>
                        </div>
                    </template>
                    <el-empty v-else description="拖拽组件到此处" />
                </div>
            </el-main>

            <!-- 右侧属性面板 -->
            <el-aside width="300px" class="right-aside">
                <div class="properties-panel">
                    <template v-if="selectedIndex !== -1">
                        <h3 class="panel-title">属性设置</h3>
                        <el-form label-position="top">
                            <!-- 基础属性 -->
                            <div class="property-section">
                                <div class="section-title">基础属性</div>
                                <el-form-item label="标签名称">
                                    <el-input v-model="formItems[selectedIndex].label" />
                                </el-form-item>
                                <el-form-item label="字段名称">
                                    <el-input v-model="formItems[selectedIndex].props.name" />
                                </el-form-item>
                            </div>

                            <!-- 验证属性 -->
                            <div class="property-section">
                                <div class="section-title">验证属性</div>
                                <el-form-item label="是否必填">
                                    <el-switch v-model="formItems[selectedIndex].props.required" />
                                </el-form-item>
                            </div>

                            <!-- 特殊属性 - 根据组件类型显示不同的属性 -->
                            <div class="property-section" v-if="getSpecialProps(formItems[selectedIndex].type)">
                                <div class="section-title">组件属性</div>
                                <template v-if="formItems[selectedIndex].type === 'input'">
                                    <el-form-item label="占位提示">
                                        <el-input v-model="formItems[selectedIndex].props.placeholder" />
                                    </el-form-item>
                                    <el-form-item label="最大长度">
                                        <el-input-number v-model="formItems[selectedIndex].props.maxlength" :min="0" />
                                    </el-form-item>
                                    <el-form-item label="显示计数器">
                                        <el-switch v-model="formItems[selectedIndex].props.showWordLimit" />
                                    </el-form-item>
                                    <el-form-item label="是否可清空">
                                        <el-switch v-model="formItems[selectedIndex].props.clearable" />
                                    </el-form-item>
                                </template>
                            </div>
                        </el-form>
                    </template>
                    <el-empty v-else description="请选择组件" />
                </div>
            </el-aside>
        </el-container>
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Delete, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { COMPONENT_LIST, COMPONENT_PROPS_CONFIG, type ComponentItem } from './constants'
import './styles.less'

interface FormItem extends ComponentItem {
    id: string;
    props: Record<string, any>;
}

const formItems = ref<FormItem[]>([])
const storageItems = ref<ComponentItem[]>([])
const selectedIndex = ref(-1)

// 添加属性编辑器组件的映射
const getPropsEditor = (type: string) => {
    // 暂时返回空组件，后续可以根据不同类型返回不同的属性编辑器
    return {
        template: '<div></div>'
    }
}

const handleDragStart = (event: DragEvent, type: string, fromStorage = false) => {
    event.dataTransfer?.setData('component-type', type)
    event.dataTransfer?.setData('fromStorage', String(fromStorage))
}

const handleDesignItemDragStart = (event: DragEvent, item: ComponentItem, index: number) => {
    event.dataTransfer?.setData('designIndex', String(index))
    event.dataTransfer?.setData('component-type', item.type)
}

const handleDrop = (event: DragEvent) => {
    event.preventDefault()
    const componentType = event.dataTransfer?.getData('component-type')
    const fromStorage = event.dataTransfer?.getData('fromStorage') === 'true'
    const designIndex = event.dataTransfer?.getData('designIndex')

    // 清除选中状态
    selectedIndex.value = -1

    if (designIndex) {
        return
    }

    const component = fromStorage
        ? storageItems.value.find(item => item.type === componentType)
        : COMPONENT_LIST.find(item => item.type === componentType)

    if (component) {
        const defaultProps = {
            ...COMPONENT_PROPS_CONFIG[component.type],
            name: '', // 添加默认的字段名称
            required: false, // 添加默认的必填属性
        }
        const newComponent: FormItem = {
            type: component.type,
            label: component.label,
            component: component.component,
            icon: component.icon,
            id: `${component.type}_${Date.now()}`,
            props: defaultProps
        }

        formItems.value = [...formItems.value, newComponent]
    }
}

const handleDropToStorage = (event: DragEvent) => {
    const componentType = event.dataTransfer?.getData('component-type')
    const designIndex = event.dataTransfer?.getData('designIndex')

    if (designIndex) {
        const item = formItems.value[Number(designIndex)]
        storageItems.value.push(item)
        formItems.value.splice(Number(designIndex), 1)
        selectedIndex.value = -1
    }
}

const removeFromStorage = (index: number) => {
    storageItems.value.splice(index, 1)
}

const handleSelectItem = (index: number) => {
    selectedIndex.value = index
}

const getSpecialProps = (type: string) => {
    return ['input', 'select', 'date', 'time'].includes(type)
}

// 添加保存和清空方法
const handleSave = () => {
    const designJson = {
        components: formItems.value.map(item => ({
            type: item.type,
            label: item.label,
            props: item.props
        }))
    }

    console.log('设计JSON:', designJson)
    ElMessage.success('设计已导出到控制台')
}

const handleClear = () => {
    ElMessageBox.confirm('确定要清空设计区吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        formItems.value = []
        selectedIndex.value = -1
        ElMessage.success('设计区已清空')
    }).catch(() => { })
}
</script>